package com.zhuhao.basic.proxy.jdk;

import com.zhuhao.basic.proxy.jdk.goal.interfacetarget.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 代理实现类，实现InvocationHandler接口
 * @Author haozhu7
 * @Date 2025/5/22 15:23
 **/
class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method invocation");
        Object result = null;
        if (target != null) {
            result = method.invoke(target, args);
        }
        System.out.println("After method invocation");

        //这里可以拿到方法名称、对应的mapper映射、具体的sql，执行真正的数据库查询逻辑
        //mybatis根据mapper的几种类型，insert、select、update、delete，执行对应的sql

        //模拟查询数据库
        if (method.getName().equals("queryAll")) {
            return new ArrayList<>(Arrays.asList(
                    new User().setAge(15).setName("小红"),
                    new User().setAge(32).setName("小楠"),
                    new User().setAge(18).setName("小艺")
            ));
        }

        //返回结果被改变
        if (result instanceof String) {
            return result + " : Proxy";
        }

        return result;

    }
}